﻿ 
using MediatR;
using MediatRApp;
using MediatRApp.Commands;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MySqlConnector;
using System.Data;

{
    var services = new ServiceCollection();
    var configuration = new ConfigurationManager();
    configuration.SetBasePath(Directory.GetCurrentDirectory());
    configuration.AddJsonFile("appsettings.json");

    services.AddLogging(configure =>
    {
        configure.AddConsole();
        configure.AddDebug();

        //configure.AddFilter((provider, categorName, level) => {
        //    return categorName.StartsWith("A.B") && level >= LogLevel.Information;
        //});

        configure.AddConfiguration(configuration.GetSection("Logging"));
    });
     

    services.AddScoped<IDbConnection>(sp =>
    { 
        var connectionString = "server=127.0.0.1;port=3306;userid=root;pwd=123456;database=ldh;Convert Zero Datetime=True;Allow User Variables=True;sslMode=None";
        return new MySqlConnection(connectionString);
    });
    services.AddScoped<DbContext>();

    services.AddMediatR(opt =>
    {
        opt.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ExceptionPipelineBehavior<,>), ServiceLifetime.Scoped);
        opt.AddBehavior(typeof(IPipelineBehavior<,>), typeof(TrsanctionPipelineBehavior<,>), ServiceLifetime.Scoped);
        opt.RegisterServicesFromAssemblyContaining<Program>();
        opt.Lifetime = ServiceLifetime.Scoped;
    });

    var sp = services.BuildServiceProvider();

    //var mediator = sp.GetRequiredService<IMediator>();
    // await mediator.Send(new CreateStudentCommand() { Name = "张三" });

    using (var scope=sp.CreateScope())
    {
        //var md = scope.ServiceProvider.GetRequiredService<IMediator>();
        //await md.Send(new CreateBookCommand() {Name= "netcore88" });

        var context = scope.ServiceProvider.GetRequiredService<DbContext>();

        var sql = "select * from biz_book;";
        var list = context.ExecuteScalar<object>(sql);
    }

}
